package com.mijie.homi.service.user;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mijie.homi.common.constant.MCKey;
import com.mijie.homi.common.domain.user.UserExtInfo;
import com.mijie.homi.dao.user.MoodUserDao;
import com.mijie.homi.domain.user.MoodUser;
import com.mijie.homi.service.cache.MemcacheService;
import com.mijie.homi.service.mood.MoodService;
import com.mijie.util.DateUtil;

@Service
public class MoodUserService {

	@Autowired
	private MoodUserDao dao;
	@Autowired
	private MoodService moodService;
	@Autowired
	private MemcacheService mcs;
	
	private Object loadMoodUserAmountLock = new Object();
	
	public List<MoodUser> listWithSameMood(Date pointInTime,UserExtInfo info,int offset,int limit,Integer gender,String order){
		return dao.listWithSameMood(pointInTime,info, offset, limit,gender,order);
	}
	
	public List<MoodUser> listWithMatchMood(UserExtInfo info,int offset,int limit,Integer gender){
		int[] mood = moodService.getMateOfMood(info.getMood());
		if(mood==null || mood.length==0) return Collections.emptyList();
		return dao.listWithMatchMood(info, mood, offset, limit, gender);
	}
	
	public synchronized void incrMoodUserAmount(int mood){
		StringBuilder key = new StringBuilder(DateUtil.getTodayStr());
		key.append(mood);
		Integer amount = getMoodUserAmount(mood);
		amount++;
		mcs.set(MCKey.MOOD_AMOUNT, key.toString(), MCKey.MOOD_CACHE_TIMEOUT, amount);
	}
	
	public Integer getMoodUserAmount(int mood){
		StringBuilder key = new StringBuilder(DateUtil.getTodayStr());
		key.append(mood);
		Integer amount = (Integer)mcs.get(MCKey.MOOD_AMOUNT, key.toString());
		if(amount==null){
			synchronized(loadMoodUserAmountLock){
				amount = (Integer)mcs.get(MCKey.MOOD_AMOUNT, key.toString());
				if(amount==null){
					amount = dao.countMoodUserAmount(mood);
					if(amount==null) amount = new Integer(0);
					mcs.set(MCKey.MOOD_AMOUNT, key.toString(), MCKey.MOOD_CACHE_TIMEOUT, amount);
				}
			}
		}
		return amount;
	}
}
